package com.atguigu.gulimall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.exception.BizCodeEnum;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.gulimall.auth.feign.MemberFeignService;
import com.atguigu.gulimall.auth.feign.ThirdPartyFeignService;
import com.atguigu.gulimall.auth.vo.UserLoginVo;
import com.atguigu.gulimall.auth.vo.UserRegistVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author 马迎迎
 * @Title: loginController
 * @Package com.atguigu.gulimall.auth.controller
 * @Description: TODO(添加描述)
 * @date 2021年05月25日 17:31
 */
@Controller
public class loginController {
    @Autowired
    private MemberFeignService memberFeignService;
    @Autowired
    private ThirdPartyFeignService thirdPartyFeignService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    /**
     * 发送一个请求直接跳转到一个页面
     * SpringMVC viewController:将请求和页面映射过来

     */
//    @GetMapping("/login.html")
//    public String loginPage(){
//        return "login";
//    }
//
//    @GetMapping("/reg.html")
//    public String regPage(){
//        return "reg";
//    }
    @ResponseBody
    @GetMapping("/sms/sendcode")
    public R sendCode(@RequestParam("mobile") String mobile){
        //TODO 1.接口防刷
        String redisCode = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + mobile);
        if(!StringUtils.isEmpty(redisCode)){
            long l = Long.parseLong(redisCode.split("_")[1]);
            if(System.currentTimeMillis()-l<=60000){
                //60s内不能再发
                return R.error(BizCodeEnum.VALID_SMS_CODE.getCode(),BizCodeEnum.VALID_SMS_CODE.getMsg());
            }
        }


        //2.验证码的再次校验 redis。存key-phone sms:code:15678283392->123456 value-code
        String code = "123456"+"_"+System.currentTimeMillis();
        System.out.println("验证码:"+code);
        //redis缓存验证码，防止60秒内一个手机号再次发送验证码

        //
        redisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX+mobile,code,10, TimeUnit.MINUTES);
//        thirdPartyFeignService.sendCode(mobile,"123456");
        return R.ok();
    }

    /**
     * //TODO 重定向携带数据，利用session原理。将数据放在session中 。
     * //只要跳到下一个页面取出这个数据后 session里的数据就会删掉
     * //TODO 分布式下的session问题
     * RedirectAttributes:重定向携带数据 利用 session原理
     * @param userRegistVo
     * @param bindingResult
     * @param redirectAttributes
     * @return
     */
    @PostMapping("/regist")
    public String register(@Valid UserRegistVo userRegistVo, BindingResult bindingResult
            , RedirectAttributes redirectAttributes){
        if(bindingResult.hasErrors()){
            Map<String,String> errorMap=new HashMap<>();
            /**
             * .map(fieldError -> {
             *                 String field=fieldError.getField();
             *                 String defaultMessage = fieldError.getDefaultMessage();
             *                 errorMap.put(field,defaultMessage);
             *
             *             })
             */
            errorMap=bindingResult.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
//            model.addAttribute("errMap",errorMap);
            redirectAttributes.addFlashAttribute("errMap",errorMap);
            //Request method 'POST' not supported
            //用户注册->/regist[post]--->转发：/reg.html(路径映射默认get方式访问) return forward:/reg.html报错
            //校验出错 转发到注册页

            return "redirect:http://auth.gulimall.com/reg.html";
        }

        //1.校验验证码
        String code = userRegistVo.getCode();
        String key=AuthServerConstant.SMS_CODE_CACHE_PREFIX+userRegistVo.getPhone();
        String s = redisTemplate.opsForValue().get(key);
        if(!StringUtils.isEmpty(s)){
            if(code.equals(s.split("_")[0])){
                //删除验证码;令牌机制
                redisTemplate.delete(key);
                //验证码通过//真正注册 调用远程服务

                R regist = memberFeignService.regist(userRegistVo);
                if(regist.getCode()==0){
                    //成功
                    return "redirect:http://auth.gulimall.com/login.html";
                }else{
                    Map<String,String> errorMap=new HashMap<>();
                    errorMap.put("msg",regist.getData("msg",new TypeReference<String>(){}));
                    redirectAttributes.addFlashAttribute("errMap",errorMap);
                    return "redirect:http://auth.gulimall.com/reg.html";
                }


            }else {
                Map<String,String> errorMap=new HashMap<>();
                errorMap.put("code","验证码错误");
                redirectAttributes.addFlashAttribute("errMap",errorMap);
                return "redirect:http://auth.gulimall.com/reg.html";
            }
        }else {
            Map<String,String> errorMap=new HashMap<>();
            errorMap.put("code","验证码错误");
            redirectAttributes.addFlashAttribute("errMap",errorMap);
            return "redirect:http://auth.gulimall.com/reg.html";
        }

        //注册成功 回到登录页
    }
    @PostMapping("/login")
    public String login(UserLoginVo vo, RedirectAttributes redirectAttributes,
            HttpSession session){
        //远程登录
        R r = memberFeignService.login(vo);
        if(r.getCode()==0){
            MemberRespVo data = r.getData("data", new TypeReference<MemberRespVo>() {
            });
            //成功 放到session中
            session.setAttribute(AuthServerConstant.LOGIN_USER,data);
            return "redirect:http://gulimall.com";
        }else {
            Map<String,String> errMap=new HashMap<>();
            errMap.put("errMap",r.getData("msg",new TypeReference<String>(){}));
            redirectAttributes.addFlashAttribute("msg",errMap);
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }
    @GetMapping("/login.html")
    public String loginPage(HttpSession session){
        if(session.getAttribute(AuthServerConstant.LOGIN_USER)==null){
            //没登录
            return "login";
        }
        return "redirect:http://gulimall.com";
    }
}
